package cn.people.dfbbs.core.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 对象复制工具类
 */
public class ObjectCopyUtils {

    private static final Logger log = LoggerFactory.getLogger(ObjectCopyUtils.class);


    /**
     * 非空复制
     * @param source 数据源对象
     * @param target 目标对象
     */
    public static void notNullCopy(Object source,Object target){
        assert source !=null && target !=null;
        Class<?> sourceClass = source.getClass();
        Class<?> targetClass = target.getClass();
        if(sourceClass!=null && targetClass!=null){
            Field[] fields = sourceClass.getDeclaredFields();
            for(Field field : fields){
                try{
                    String name = field.getName();
                    targetClass.getDeclaredField(name); // 判断源属性在目标属性中是否存在
                    Class<?> type = field.getType();
                    String getMethodName = "get"+name.substring(0,1).toUpperCase()+name.substring(1);
                    String setMethodName = "set"+name.substring(0,1).toUpperCase()+name.substring(1);
                    Method getMethod = sourceClass.getMethod(getMethodName);
                    Method setMethod = targetClass.getMethod(setMethodName,type);
                    Object invoke = getMethod.invoke(source);
                    if(invoke !=null && invoke!=""){
                        setMethod.invoke(target,invoke);
                    }
                } catch (NoSuchFieldException e) {
                    log.debug("从目标对象[{}]中没有找到[{}]属性",targetClass.getSimpleName(),field.getName());
                } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
